﻿using PagedList;
using SIG.Infrastructure.Configs;
using SIG.Model;
using SIG.Service;
using SIG.ViewModel;
using SIG.ViewModel.Admin;
using SIG.WebMVC.Filters;
using System;
using System.Web.Mvc;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class LogsController : BaseController
    {
        ILogService _LogService;

        public LogsController(ILogService LogService)
        {
            _LogService = LogService;

        }

      
        public ActionResult Index(int? page, DateTime? startDate, DateTime? expireDate, string level)
        {
            var logSearchVM = new LogSearchVM();

            logSearchVM.StartDate = startDate;
            logSearchVM.ExpireDate = expireDate;
            logSearchVM.Level = level;

            logSearchVM.PageIndex = (page ?? 1) - 1;
            logSearchVM.PageSize = SettingsManager.Log.PageSize;
            logSearchVM.Logs = _LogService.SearchLogs(logSearchVM.PageIndex, logSearchVM.PageSize, startDate, expireDate, level);
            logSearchVM.TotalUserCount = _LogService.SearchLogsCount(startDate, expireDate, level);

            var logsAsIPagedList = new StaticPagedList<Log>(logSearchVM.Logs, logSearchVM.PageIndex + 1, logSearchVM.PageSize, logSearchVM.TotalUserCount);
            ViewBag.OnePageOfLogs = logsAsIPagedList;

            return View(logSearchVM);

        }


    
        [HttpPost]  
        public JsonResult Delete(string id)
        {
            if (id == "all")
            {
                int count = _LogService.RemoveAll();
                if (count > 0)
                {
                    AR.SetSuccess("已清空所有日志");
                    return Json(AR, JsonRequestBehavior.DenyGet);
                }                   
            }
            else
            {
                
                int logId;
                Int32.TryParse(id, out logId);

                var log = _LogService.GetById(logId);
                _LogService.Delete(log);

                AR.SetSuccess("已成功删除日志");
                return Json(AR, JsonRequestBehavior.DenyGet);            
               
            }

            AR.Setfailure("删除日志失败");
            return Json(AR, JsonRequestBehavior.DenyGet);          
        }
            
    }
}